//
//  SeekoArticleContentWebView.m
//  MokoAPP
//
//  Created by 현식 강 on 11. 8. 5..
//  Copyright 2011 아이온. All rights reserved.
//

#import "SeekoArticleContentWebView.h"
#import "SeekoArticleTableViewController.h"
#import "MokoAppDelegate.h"
@implementation SeekoArticleContentWebView
@synthesize tableController;

-(void)awakeFromNib {
    naverButtonPath = [[NSBundle mainBundle] resourcePath];
    naverButtonPath = [naverButtonPath stringByReplacingOccurrencesOfString:@"/" withString:@"//"];
    naverButtonPath = [naverButtonPath stringByReplacingOccurrencesOfString:@" " withString:@"%20"];
    naverButtonPath = [[NSString alloc] initWithString:[NSString stringWithFormat:@"file:/%@//bg_btn_default.gif", naverButtonPath]];
}

-(void)loadHTMLString:(NSString *)contentString images:(NSString*)imageString links:(NSString*)linkString baseURL:(NSURL *)baseURL {
    NSString* path = [[NSBundle mainBundle] pathForResource: @"contentHeaderAndFooter" ofType: @"html"];
    NSError* error;
    NSString* html = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:&error];
    GET_APPDELEGATE;
    imageString = [imageString stringByReplacingOccurrencesOfString:@"src=\"data/" withString:[NSString stringWithFormat:@"src=\"%@/zboard4/data/", delegate.configVO.siteHostAddress]];
    html = [html stringByReplacingOccurrencesOfString:@"#images#" withString:
            imageString];
    html = [html stringByReplacingOccurrencesOfString:@"#links#" withString:linkString];
    html = [html stringByReplacingOccurrencesOfString:@"#button#" withString:naverButtonPath];
    html = [html stringByReplacingOccurrencesOfString:@"#width#" withString:[NSString stringWithFormat:@"%f", self.frame.size.width]];
    html = [html stringByReplacingOccurrencesOfString:@"#showImage#" withString:([delegate.configVO.showImageInArticle boolValue] == YES) ? @"true" : @"false"];
    // 데이터 치환 문제 발생을 원천 봉쇄하기 위해 맨 마지막에 내용을 교체
    html = [ html stringByReplacingOccurrencesOfString:@"#content#" withString:contentString];
    [super loadHTMLString:html baseURL:baseURL];
}
-(BOOL) webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    if( [[[request URL] absoluteString] isEqualToString:@"callback:imageloaded"] == YES ) {
        [self calculateWebViewSize:[self stringByEvaluatingJavaScriptFromString:@"document.getElementById('links').offsetHeight + document.getElementById('imageButton').offsetHeight + document.getElementById('bodytable').offsetHeight + document.getElementById('images').offsetHeight + 30"]];
        return NO;
    }
    else if( navigationType == UIWebViewNavigationTypeLinkClicked ) {
        [[UIApplication sharedApplication] openURL:[request URL]];
        return NO;
    }
    return YES;
}

- (void) webViewDidFinishLoad:(UIWebView *)sender {
    prevFrame = self.frame;
    NSString* size = [self stringByEvaluatingJavaScriptFromString:@"document.getElementById('links').offsetHeight + document.getElementById('imageButton').offsetHeight + document.getElementById('bodytable').offsetHeight + document.getElementById('images').offsetHeight + 30"];
    if( [size floatValue] != 0 ) {
        [self performSelectorOnMainThread:@selector(calculateWebViewSize:) withObject:size waitUntilDone:YES];

    }
    else {
        NSString* scrollSize = [self stringByEvaluatingJavaScriptFromString:@"document.documentElement.scrollHeight"];
        [self performSelectorOnMainThread:@selector(calculateWebViewSize:) withObject:scrollSize waitUntilDone:YES];
    }
}
-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
    UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"웹페이지 로드 실패" message:@"네트워크 상의 문제가 있습니다. 네트워크를 확인하시기 바랍니다." delegate:nil cancelButtonTitle:nil otherButtonTitles:@"확인", nil];
    [alert show];
    [alert release];
}
-(void)dealloc {
    [tableController release];
    [naverButtonPath release];
    [super dealloc];
}
- (void)calculateWebViewSize:(NSString*)newHeight {
    //size the notes view
    CGFloat nHeight = [newHeight floatValue];
    //self.scalesPageToFit = YES;
    float addHeight = nHeight - prevFrame.size.height;
    CGRect newFrame = self.frame;
    newFrame.size.width = [[UIScreen mainScreen] bounds].size.width;
    newFrame.size.height = nHeight;
    self.frame = newFrame;
    //NSLog(@"%f", self.frame.size.width);
    float maxY = 0;
    for( UIView* subview in [self.superview subviews] ) {
        if( subview.hidden == NO ) {
            CGRect subFrame = subview.frame;
            // 웹뷰보다 아래에 있는 객체라면 웹뷰가 늘어난 만큼 아래로 밀기
            if( self.frame.origin.y < subFrame.origin.y ) {
                subFrame.origin.y += addHeight;
                subview.frame = subFrame;
            }
            
        }
    }
    for( UIView* subview in [self.superview subviews] ) {
        if( subview.hidden == NO ) {
            maxY = MAX(maxY, (subview.frame.size.height + subview.frame.origin.y));
        }
    }
    newFrame = self.superview.frame;
    newFrame.size.height = maxY + 10;
    self.superview.frame = newFrame;
    prevFrame = self.frame;
    tableController.tableView.tableHeaderView = self.superview;
}

@end
